/**
 * 乘积最大子数组
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function (nums) {
  let maxProd = nums[0];
  let currentMax = maxProd;
  let currentMin = maxProd;

  for (let i = 1; i < nums.length; i++) {
    // if we hit a negative number, our max is now min and min is now max
    if (nums[i] < 0) {
      const temp1 = currentMax;
      currentMax = currentMin;
      currentMin = temp1;
    }
    currentMax = Math.max(nums[i], nums[i] * currentMax);
    currentMin = Math.min(nums[i], nums[i] * currentMin);
    maxProd = Math.max(currentMax, maxProd);
  }

  return maxProd;
};

console.log(maxProduct([2, 3, -2, 4])) // 6
console.log(maxProduct([-2, 0, -1])) // 0  结果不能为 2, 因为 [-2,-1] 不是子数组。